﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestApi.Models;
using Microsoft.Extensions.Http;
using System.Net.Http;
using TestApi.Db;
using Newtonsoft.Json;
using AutoMapper;
using System.Text;
using System.IO;

namespace TestApi.Services
{
    public class TestService
    {
        private readonly IHttpClientFactory clientFactory;
        private readonly GithubDbContext db;
        private readonly IMapper mapper;

        public TestService(IHttpClientFactory clientFactory, GithubDbContext db, IMapper mapper)
        {
            this.clientFactory = clientFactory;
            this.db = db;
            this.mapper = mapper;
        }
        JsonSerializerSettings setting = new JsonSerializerSettings()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            NullValueHandling = NullValueHandling.Ignore
        };

     
        public async Task<ResultDto> Loading(string repo)
        {
            await GitHubData(repo);
            ResultDto result = new ResultDto();

            var query = db.Rights.Join(db.Lefts, right => right.LeftId, left => left.Id, (right, left) => new RightDto { Id = right.Id, name = left.Name, LeftId = left.Id });
            result.Rights = query.ToList();

            var list = db.Lefts.Where(x => !x.IsRight);
            result.Lefts = mapper.Map<IList<LeftDto>>(list);

            var dtos = mapper.Map<IList<LeftDto>>(db.Lefts);
            return result;
        }

        private async Task GitHubData(string repo)
        {
            string url = string.Format("https://api.github.com/orgs/{0}/repos", repo);
            var client = clientFactory.CreateClient();
            client.DefaultRequestHeaders.Add("accept", "application/vnd.github.v3+json");
            client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36");
            var repos = await client.GetAsync(url);
            if (repos == null)
            {
                throw new Exception("请求Github 失败");
            }
            var str = await repos.Content.ReadAsStringAsync(); 
            str = str.Replace("private", "XXXX");  
            IList<GithubDto> githubs = JsonConvert.DeserializeObject<IList<GithubDto>>(str, setting);
            var lefts = mapper.Map<IList<Left>>(githubs);
            db.Lefts.RemoveRange(db.Lefts);
            db.Rights.RemoveRange(db.Rights);
            await db.Lefts.AddRangeAsync(lefts);
            await db.SaveChangesAsync();
        }

        public async Task<ResultDto> Right(List<LeftDto> lefts)
        {
            var models = mapper.Map<IList<Right>>(lefts); 
            await db.Rights.AddRangeAsync(models);

            foreach (var item in lefts)
            {
                var left = db.Lefts.FirstOrDefault(x => x.Id == item.Id);
                db.Attach(left);
                left.IsRight = true;
            }
            await db.SaveChangesAsync();

            IList<RightDto> dtos = new List<RightDto>();
            List<int> leftIds = lefts.Select(x => x.Id).ToList();
            var query = db.Rights.Join(db.Lefts, right => right.LeftId, left => left.Id, (right, left) => new RightDto { Id = right.Id, name = left.Name, LeftId = left.Id });

            ResultDto result = new ResultDto();
            result.Rights = query.ToList();

            var list = db.Lefts.Where(x => !x.IsRight);
            result.Lefts = mapper.Map<IList<LeftDto>>(list);

            return result;


        }


        public async Task<ResultDto> Left(List<RightDto> rights)
        {
            var models = mapper.Map<IList<Right>>(rights);

            db.Rights.RemoveRange(models);

            foreach (var item in rights)
            {
                var left = db.Lefts.FirstOrDefault(x => x.Id == item.Id);
                db.Attach(left);
                left.IsRight = false; ;
            }
            await db.SaveChangesAsync();


            var query = db.Rights.Join(db.Lefts, right => right.LeftId, left => left.Id, (right, left) => new RightDto { Id = right.Id, name = left.Name, LeftId = left.Id });

            ResultDto result = new ResultDto();
            result.Rights = query.ToList();
            var list = db.Lefts.Where(x => !x.IsRight);
            result.Lefts = mapper.Map<IList<LeftDto>>(list);

            return result;
        }

        public async Task<string> Email()
        {
            var list = db.Lefts.Where(x => x.IsRight).ToList();
            StringBuilder builder = new StringBuilder();
            builder.Append("hi Test");
            builder.Append("<br/>");
            builder.Append("<br/>");
            builder.Append("This is your favor repos");
            builder.Append("<br/>");
            foreach (var item in list)
            {
                builder.Append("-" + item.Description);
                builder.Append("<br/>");
                builder.Append("-" + item.HtmlUrl);
                builder.Append("<br/>");
            }
            return builder.ToString();
        }
    }

}
